// pages/databaseGuide/databaseGuide.js
const app = getApp()
var nickName
var avatarUrl
var names
Page({
  
  data: {
    openid: '',
    queryResult: '',
    selectData: [
      { "id": 1, "name": "最后一次，下次再戒" },
       { "id": 2, "name": "戒了这么久，可以放松一下了" }, 
       { "id": 3, "name": "只看不撸，就看看" }, 
       { "id": 4, "name": "只撸不射，没事的" },
       { "id": 5, "name": "撸一发，好睡觉" },
       { "id": 6, "name": "憋精有害，要射掉" },
       { "id": 7, "name": "已经撸了，再撸几次也一样" },
       { "id": 8, "name": "试一下自己到底行不行" },
       { "id": 9, "name": "最近学习进步了，奖励自己一次" },
       { "id": 10, "name": "就意淫一下，不会破戒的" },
      ],
    imgbox: [],//选择图片
    fileIDs: [],//上传云存储后的返回值
    nickName:'',
    avatarUrl:'',
    isLogin:0
  },
  onShow: function () {
    var that=this
    names=''
    wx.getStorage({
      key: 'user',
      success: function(res) {
        nickName = res.data.nickName
        avatarUrl = res.data.avatarUrl
        that.setData({
          isLogin: 1,
          nickName:res.data.nickName,
          avatarUrl:res.data.avatarUrl
        })
      }, fail () {
        
      }
    })
  },
   
  onLoad: function (options) {
    var date = new Date();
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '';
    this.setData({
      date: Y + M + D
    })
  },

  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    console.log("长度:" + e.detail.value.length);
    app.globalData.status = e.detail.value

    this.setData({

      id: e.detail.value,
      length: e.detail.value.length,
      
    })
    names=e.detail.value.join('  |  ')
  },

  radioChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    console.log("长度:" + e.detail.value.length);
    app.globalData.temperature = e.detail.value
   
    this.setData({
      id: e.detail.value,
      length: e.detail.value.length,
      
    })
  },

  onAdd: function (e) {
    var that=this
    if (names == null || names == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择心魔'
      })
      return false
    }
    wx.showModal({
      title: '提示',
      content: '确定要提交吗？',
      success: function (sm) {
          if (sm.confirm) {
            wx.showLoading({
              title: '数据提交中',
            })
            const db = wx.cloud.database()

            var date = new Date();
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '  ';
            var DD = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) ;
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
            //1、判断是有效打卡还是无效打卡，有效打卡状态为1，无效打卡状态为0
        
            //2、查询状态为是否存在打卡记录
            wx.cloud.callFunction({
              name: 'getopenid',//调用云函数获取用户唯一openid
              complete: res => {
                const openid = res.result.openid
                db.collection('ranking').where({
                  _openid: openid,
                })
                .get({
                  success: function(res) {
           
                    if(res.data.length==0&&Object.keys(res.data).length === 0){//如果原先没有记录
                   
                      db.collection('ranking').add({ //插入记录ranking
                        data: {
                          create_time: Y+M+D+h+m+s,
                          date:Y+M+DD,
                          nickName:that.data.nickName,
                          avatarUrl:that.data.avatarUrl,
                          count:1
                        }
                      }).then(res => {          
                              db.collection('record').add({
                                data: {
                                  create_time: Y+M+D+h+m+s,
                                  date:Y+M+DD,
                                  nickName:that.data.nickName,
                                  avatarUrl:that.data.avatarUrl,
                                  name: names,
                                  remark: e.detail.value.remark,
                                }
                              }).then(res => {
                               
                                  wx.showToast({
                                    title: '一定要戒撸！',
                                    icon: 'success',
                                    duration: 2000
                                  })
                                
                                
                              }).catch(console.error)
                      }).catch(console.error)
                    }else if(res.data.length>0&&Object.keys(res.data).length > 0){//如果存在记录
                      
                        db.collection('ranking').where({
                          _openid: openid,
                        }).update({ //更新记录ranking
                          data: {
                            create_time: Y+M+D+h+m+s,
                            date:Y+M+DD,
                            count:res.data[0].count+1
                          }
                        }).then(res => {  
                              db.collection('record').add({
                                data: {
                                  create_time: Y+M+D+h+m+s,
                                  date:Y+M+DD,
                                  nickName:that.data.nickName,
                                  avatarUrl:that.data.avatarUrl,
                                  name: names,
                                  remark: e.detail.value.remark,
                                }
                              }).then(res => {
                                wx.showToast({
                                  title: '一定要戒撸！',
                                  icon: 'success',
                                  duration: 2000
                                })
                              }).catch(console.error)
                        }).catch(console.error)
                      
                      
                    }
                    wx.hideLoading()
                    setTimeout(() => {    
                      wx.reLaunch({
                        url: '../index/index',
                      })
                    }, 2000); 
                    
                  },
                    fail: err => {
                      wx.hideLoading()
                      console.error('[数据库] [新增记录] 失败：', err)
                    }
                })
              }
            })

          } else if (sm.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    

  },

  onPullDownRefresh: function () {
    this.updateBlogs()
  },
  updateBlogs: function () {
    this.onQuery()
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },

  onQuery: function () {
    const db = wx.cloud.database()
    //查询当前用户所有的 counters
    db.collection('PVERSION').where({
        version: 2019
    }).orderBy('time', 'desc').get({
      success: res => {
        this.setData({
          queryResult: res.data
        })
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  goHome: function() {
    const pages = getCurrentPages()
    if (pages.length === 2) {
      wx.navigateBack()
    } else if (pages.length === 1) {
      wx.redirectTo({
        url: '../index/index',
      })
    } else {
      wx.reLaunch({
        url: '../index/index',
      })
    }
  }
})